
import os
from docx import Document
import requests

def read_and_number_headings(doc_path):
    # 确保文件
    if not os.path.exists(doc_path):
        print(f"ERROR: 文件未找到 -> {doc_path}")
        return {}

    # 读取文档
    doc = Document(doc_path)
    print(f"成功打开文件 -> {doc_path}")

    # 存储每一层级的编号
    heading_numbers = []

    # 存储标题和对应内容的字典
    headings_dict = {}

    print("开始遍历标题段落...")

    last_number = None  # 记录最后一次处理的编号，避免出现跳跃

    # 遍历段落，检查每个段落的样式是否为标题样式
    for para in doc.paragraphs:
        text = para.text.strip()
        style_name = para.style.name
        
        # 只处理包含"Heading"的段落（标题段落）
        if "Heading" in style_name:
            # 获取当前层级
            heading_level = int(style_name.split(' ')[-1])  # 获取 Heading 级别，例如 Heading 1 -> 1, Heading 2 -> 2
            
            # 如果当前层级大于现有的层级，说明是一个子标题，需扩展编号
            if heading_level > len(heading_numbers):
                for i in range(heading_level-len(heading_numbers)):
                    heading_numbers.append(1)  # 新增层级从1开始
            elif heading_level < len(heading_numbers):
                # 如果当前层级小于之前的层级，删除尾部多余的部分
                heading_numbers = heading_numbers[:heading_level]

                # 更新当前层级的编号
                heading_numbers[heading_level - 1] += 1

            else:
                # 如果当前层级等于现有层级，递增该层级的编号
                heading_numbers[heading_level - 1] += 1

            # 生成编号内容
            heading_number = '.'.join(map(str, heading_numbers))
            
            # 如果编号与上一行相同，表示跳跃编号，跳过当前段落
            if last_number == heading_number:
                continue

            last_number = heading_number  # 更新上一编号
            
            # 保存标题和对应内容到字典
            if heading_number not in headings_dict:
                headings_dict[heading_number] = {"title": text, "content": []}
            else:
                headings_dict[heading_number]["title"] = text

            # 打印输出，标题对齐
            print(f"{heading_number:<10} {text}")
        
        else:
            # 将非标题段落内容添加到字典对应的标题下
            if heading_numbers:
                heading_number = '.'.join(map(str, heading_numbers))
                headings_dict[heading_number]["content"].append(text)
    
    return headings_dict

def call_ai_api(content):
    """
    调用 AI API，返回功能点分析结果。
    content: 单个段落内容
    """
    api_url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "103f067729ac42b2a159f9a66a281dd7.Q2IQv5mgWbidoacD"  # 替换为你的 API Key
    }
    
    question = f"以下这一段的软件功能点是什么？请使用短句简要回答，除了功能点以外不回复其他内容，回答内容采用,隔开{content}"
    
    payload = {
        "model": "chatglm_6b",
        "messages": [{"role": "user", "content": question}]
    }
    
    try:
        response = requests.post(api_url, json=payload, headers=headers)
        if response.status_code == 200:
            result = response.json()
            return result.get("choices")[0].get("message").get("content")
        else:
            print(f"API请求失败，状态码: {response.status_code}")
            return None
    except Exception as e:
        print(f"调用API时出现错误: {e}")
        return None

def analyze_paragraphs_with_api(headings_dict):
    """
    遍历所有段落内容，调用 AI API 获取功能点分析结果。
    """
    results = {}

    for heading_number, heading_data in headings_dict.items():
        print(f"\n分析标题编号: {heading_number}, 标题: {heading_data['title']}")
        
        # 遍历标题下的所有段落内容
        for i, paragraph in enumerate(heading_data["content"]):
            print(f"调用 API 处理段落 {i+1}...")
            api_result = call_ai_api(paragraph)
            
            if api_result:
                print(f"API 分析结果: {api_result}")
            else:
                print(f"段落 {i+1} 分析失败")
            
            # 将结果存储到字典中
            if heading_number not in results:
                results[heading_number] = []
            
            results[heading_number].append({
                "paragraph": paragraph,
                "analysis": api_result
            })

    return results

# 文件路径
doc_path = "/Users/guhaoyu/Desktop/造价AI工作/2、客户提供的建设需求或可研文档/01.docx"

# 读取和编号标题
headings_dict = read_and_number_headings(doc_path)

# 调用 API 分析段落内容
results = analyze_paragraphs_with_api(headings_dict)

# 打印或保存结果
print("\n分析完成，结果如下:")
for heading_number, paragraphs in results.items():
    print(f"\n标题编号: {heading_number}")
    for item in paragraphs:
        print(f"段落: {item['paragraph']}")
        print(f"分析结果: {item['analysis']}")
